/**
 * Created by Dalyn on 2017/5/19.
 * 需求数量弹框
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import InputBox from "../../../common/InputBox"
import { Modal,Table,message,Input } from 'antd';
import ReactKey from "../../../util/ReactKey";
import GetPlanNeedCountMutation from "./mutation/GetPlanNeedCountMutation";
import "../css/fabricRaw.css";
import "../css/productionManagement_common.css";

export default class DemandQuantityModal extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            loading:false,
            sumQuantity:0,
            dataSource:[],
            DemandQuantityFlag:false,
        };
        this.style = {

        };
        this.list=[];
        this.sumQuantity = 0;
    }
    componentWillMount(){
        // this.getPlanNeedCount()
        // this.dataSource=this.props._planNeedCountModelList;
        this.setState({
            dataSource:this.props._planNeedCountModelList,
        })
    }
    /*原来获取单个的需求数接口*/
    getPlanNeedCount(planId){
        if(planId){
            Relay.Store.commitUpdate(
                new GetPlanNeedCountMutation({
                    planId:planId || "",
                }),
                {
                    onFailure: () => {
                        message.error("网络请求失败")
                        this.setState({
                            loading: false
                        })
                    },
                    onSuccess: (response) => {
                        let errorCode = response.getPlanNeedCount.responseData.errorCode
                        if (errorCode == 0) {
                            let planNeedCountModelList = response.getPlanNeedCount.responseData.planNeedCountModelList
                            const newData = {
                                planId: this.props.planId || null,
                                needCountId:null,
                                dosage: null,
                                expend: null,
                                needCount: null,
                                sizeGroup: null,
                                compactCount: null,
                            };
                            if (!planNeedCountModelList.length) {
                                planNeedCountModelList.push(newData);
                            }
                            this.setState({
                                dataSource:[...planNeedCountModelList,newData],
                                loading: false
                            })
                        } else if(errorCode == 500){
                            this.setState({
                                loading:false,
                            });
                            message.error('服务器错误，请联系系统管理员')
                        }
                    }
                }
            );
        }else {
            /*没有planId,数据为空默认加一行,最后一行是总数*/
            const { dataSource } = this.state;
            const newData = {
                planId: this.props.planId || null,
                needCountId:null,
                dosage: null,
                expend: null,
                needCount: null,
                sizeGroup: null,
                compactCount: null,
            };
            this.setState({
                dataSource: [...dataSource, newData,newData],
                loading:false,
            });
        }
    }
    /*没用*/
    componentWillReceiveProps(){
        /*this.setState({
            dataSource:this.props._planNeedCountModelList,
        })*/
    }
    /*点击确定*/
    handleOk(){
        let {dataSource} = this.state;
        let dataSelf = JSON.parse(JSON.stringify(this.state.dataSource));
        let req = /^\s*$/g;
        let compactCount_flag = true,
            dosage_flag = true,
            expend_flag = true;
        let emptySizeGroup = false,
        emptyCompactCount = false,
            emptyDosage = false,
            emptyExpend = false;
        //删除最后一条-求和项,再做判断
        // console.log(dataSelf);
        dataSelf.pop();
        dataSelf.map((item,index)=>{
            emptySizeGroup = item.sizeGroup==null||item.sizeGroup==""||item.sizeGroup==undefined||req.test(item.sizeGroup);
            emptyCompactCount = item.compactCount==0||item.compactCount==null||item.compactCount==""||item.compactCount==undefined||req.test(item.compactCount);
            emptyDosage =item.dosage==0||item.dosage==null||item.dosage==""||item.dosage==undefined||req.test(item.dosage);
            emptyExpend =item.expend==0||item.expend==null||item.expend==""||item.expend==undefined||req.test(item.expend);
            /*三个都不能为空*/
            if( emptyCompactCount){
                compactCount_flag=false;
            }
            if(emptyDosage){
                dosage_flag=false;
            }
            if(emptyExpend){
                expend_flag=false;
            }
        });
        if(compactCount_flag && dosage_flag && expend_flag){
            this.props._demandQuantity(this.props._demandQuantityIndex,this.sumQuantity,dataSelf);
        }else {
            // message.warning(<span>带<span className="red">*</span>号为必填项</span>)
            message.warning("请填写正确数据")
        }
    }
    handleCancel = (e) => {
        this.setState({
            DemandQuantityFlag: false,
            dataSource: [],
        });
    };
    /*删除行*/
    onDelete(index,materialDetailId) {
        const dataSource = [...this.state.dataSource];
        dataSource.splice(index, 1);
       /* if (materialDetailId) {
            this.proMaterialIds.push(materialDetailId)
            this.setState({
                proMaterialIds: this.proMaterialIds
            });
        }*/
        this.setState({
            dataSource,
        });
    }
    /*添加行*/
    handleAdd = () => {
        const { dataSource } = this.state;
        if(dataSource.length>=6){
            message.warning("最多添加5条");
            return;
        }
        const newData = {
                planId: this.props._planId || null,
                needCountId:null,
                dosage: null,
                expend: null,
                needCount: null,
                sizeGroup: null,
                compactCount: null,
        };
        dataSource.splice(dataSource.length-1,0,newData);
        this.setState({
            dataSource: dataSource,
            // dataSource: [...dataSource, newData],
        });
    };
    /*手动输入*/
    InputChange(contextname,index,e){
        let dataSource = this.state.dataSource;
        if(!dataSource[index]){
            dataSource[index] = {}
        }
        let text = e.target.value;
        let reg1 =  /^([0-9]{0,10})$/;
        let reg3 =  /^([0-9]{0,7})+\.?([0-9]{0,4})$/;
        if (contextname == 'compactCount') {
            text = Number(text) == NaN? "" : Number(text);
            if (!reg1.test(text) ) {
                e.target.value =  null;
                return
            } else if (text.length > 10){
                e.target.value = e.target.value.toString(0,10);
                return
            }
            /*数据计算*/
            //
        }
        if (contextname == 'dosage') {
            // let dosageText = reg3.exec(text)[1];
            // let dosageDot = reg3.exec(text)[2];
            if (!reg3.test(text) ) {
                e.target.value =  '';
                return
            } else if (text.length > 7){
                /*dosageText.length > 10||dosageDot.length>3*/
                e.target.value = e.target.value.toString(0,7);
                return
            }
            /*数据计算？？？？？？*/
            //
        }
        if (contextname == 'expend') {
            if (!reg3.test(text) ) {
                e.target.value =  '';
                return
            } else if (text.length > 7){
                e.target.value = e.target.value.toString(0,5);
                return
            }
        }
        if (contextname == 'sizeGroup') {
            let str_temp = text.replace(/[\u4e00-\u9fa5]/g, 'aa')//将汉字替换为aa
            if (str_temp.length > 50) {
                e.target.value = text.toString(0,50)
                return
            }
        }

        let context = dataSource[index];
        context[contextname] = text;
        this.setState({
            context: context,
            dataSource: dataSource
        },()=>{
            // console.log(this.state.dataSource);
        });
    }
    /*总需求数计算*/
    sumDemandQuantity(){
        let dataSource = this.state.dataSource;
        let sum = 0;
        dataSource.map((v,i)=>{
            if(i== dataSource.length-1)return;
            sum+=(v.compactCount*v.dosage*v.expend)
        });
        /*this.setState({
            sumQuantity:sum.toFixed(2)
        });*/
        sum = (sum+"") == "NaN" ? "0" : sum;
        this.sumQuantity=Math.round(sum);
        return Math.round(sum)
    }
    render(){
        const { dataSource } = this.state;
        // console.log(dataSource);
        const columns = [
            {
            title: '尺码组',
            dataIndex: 'sizeGroup',
            key: 'sizeGroup',
            width: 200,
            render: (text, record, index) => {
                const obj  = {
                    children:text,
                    props:{},
                };
                if(index == dataSource.length-1){
                    obj.children = <span className="production_fabricRaw_demandQualityModal_sum">总需求数</span>;
                    obj.props.colSpan  = 4;
                    return obj
                }else {
                    return <input
                        className="prodution_fabricRaw_edit_input_edit"
                        onChange={this.InputChange.bind(this,'sizeGroup',index)}
                        value={record.sizeGroup}
                        type="text" key={record.needCountId+"sizeGroup"}
                        ref={"sizeGroup"}
                    />
                }
            },
        },
            {
            title: <span><i className="red">*</i>合同数</span>,
            dataIndex: 'compactCount',
            key: 'compactCount',
            width: 200,
            render: (text, record, index) => {
                const obj  = {
                    children:text,
                    props:{},
                };
                if(index == dataSource.length-1){
                    obj.props.colSpan  = 0;
                    return obj
                }else {
                    return <input maxLength="10" key={record.needCountId+"compactCount"}
                        className="prodution_fabricRaw_edit_input_edit"
                        value={record.compactCount}
                        onChange={this.InputChange.bind(this,'compactCount',index)}
                        type="text" ref={"compactCount"}/>
                }
            },
        },
            {
            title:<span><i className="red">*</i>用量/件</span>,
            dataIndex: 'dosage',
            key: 'dosage',
            width: 200,
            render: (text, record, index) => {
                const obj  = {
                    children:text,
                    props:{},
                };
                if(index == dataSource.length-1){
                    obj.props.colSpan  = 0;
                    return obj
                }else {
                    return <input maxLength="7"
                                className="prodution_fabricRaw_edit_input_edit"
                                value={record.dosage}
                                onChange={this.InputChange.bind(this,'dosage',index)}
                                type="text" ref={"dosage"}
                                  key={record.needCountId+"dosage"}
                            />
                }
            },
        },
            {
                title:<span><i className="red">*</i>损耗</span>,
                dataIndex: 'expend',
                key: 'expend',
                width: 200,
                render: (text, record, index) => {
                    const obj  = {
                        children:text,
                        props:{},
                    };
                    if(index == dataSource.length-1){
                        obj.props.colSpan  = 0;
                        return obj
                    }else {
                        return <input maxLength="5"
                                      className="prodution_fabricRaw_edit_input_edit"
                                      value={record.expend}
                                      onChange={this.InputChange.bind(this,'expend',index)}
                                      type="text" ref={"expend"}
                                      key={record.needCountId+"expend"}
                        />
                    }
                },
            },
            {
            title: '需求数',
            dataIndex: 'needCount',
            key: 'needCount',
            width: 300,
            render: (text, record, index) => {
                const obj  = {
                    children:text,
                    props:{},
                };
                if(index == dataSource.length-1){
                    obj.children = <span className="production_fabricRaw_demandQualityModal_sum">{this.sumDemandQuantity()}</span>;
                    obj.props.colSpan  = 1;
                    return obj
                }else {
                    let num = Math.round(Number(record.compactCount*record.dosage*record.expend));
                    num = (num+"") == "NaN" ? "0"  : num;
                    return <span ref={"needCount"}>{num}</span>
                }
            },
        },
            {
            title: '',
            dataIndex: 'op',
            key: 'op',
            width: 200,
            render: (text, record, index) => {
                const obj  = {
                    children:text,
                    props:{},
                };
                if(index == dataSource.length-1){
                    obj.props.colSpan  = 2;
                    return obj
                }else {
                    if (index == this.state.dataSource.length-2) {
                        if (index != 0) {
                            return (
                                <span>
                                <a className="order_from_sp_add" onClick={this.handleAdd.bind(this)}></a>&nbsp;
                                    <a className="order_from_sp_minus" onClick={this.onDelete.bind(this, index, record.materialDetailId)}></a>
                            </span>
                            )
                        } else {
                            return (<a className="order_from_sp_add" onClick={this.handleAdd}></a>)
                        }
                    } else {
                        return (
                            <a className="order_from_sp_minus" onClick={this.onDelete.bind(this, index, record.materialDetailId)}></a>
                        )
                    }
                }
            },
        }];
        return (
            <Modal title="需求数列表"
                   visible={this.state.DemandQuantityFlag}
                   style={{width:"800px", top : '20%',left : '-1%' }}
                   wrapClassName="batchhint_modal demand_quality_modal"
                   onOk={this.handleOk.bind(this)}
                   onCancel={this.handleCancel.bind(this)}
                   okText="确定"
                   cancelText="取消"
                   maskClosable={false}
            >
                <div>
                    <Table
                        columns={columns}
                        dataSource={dataSource}
                        bordered
                        style={{width:'600px',marginBottom:"10px"}}
                        className="order_table production_management_modal"
                        pagination={false}
                        loading={this.state.loading}
                    />
                </div>

                <div className="productionManagement_red">需求数 = 合同数 * 用量/件 * 损耗</div>
            </Modal>
        )
    }
}
